package com.itwzy.bookshop.DAO;

import com.itwzy.bookshop.Bean.AdminsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
public class AdminDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据账号和密码查询管理员
     * @param account
     * @param pass
     * @return
     */
    public AdminsBean selectByAccountAndPass(String account, String pass){
        String sql="SELECT admin_id,account,pass,nick_name FROM admins WHERE account=? AND pass=?";
        List<AdminsBean> admins = new ArrayList<>();
        admins = jdbcTemplate.query(sql
                , new RowMapper<AdminsBean>() {
            @Override
                    public  AdminsBean mapRow(ResultSet re,int rowNum) throws SQLException{
                AdminsBean admin =new AdminsBean();
                admin.setAdminId(re.getInt("admin_id"));
                admin.setAccount(re.getString("account"));
                admin.setPass(re.getString("pass"));
                admin.setNickName(re.getString("nick_name"));
                return admin;
            }
                },account,pass);
        return admins==null || admins.size()==0?null:admins.get(0);
    }

    /**
     * 修改密码
     * @param account
     * @param pass
     * @return
     */
    public int updatePass(String account,String pass){
        String sql="UPDATE admins SET pass = ? WHERE account=?";
        return jdbcTemplate.update(sql,pass,account);
    }

    /**
     * 修改管理员
     * @param admin
     * @return
     */
    public int updateAdmin(AdminsBean admin){
        String sql = "UPDATE admins SET account = ?,nick_name = ?WHERE admin_id = ?";
        return jdbcTemplate.update(sql,admin.getAccount(),admin.getNickName(),admin.getAdminId());
    }

    /**
     * 根据id查询管理员
     * @param id
     * @return
     */
    public AdminsBean selectById(String id){
        String sql="SELECT admin_id,account,pass,nick_name FROM admins WHERE admin_id=?";
        List<AdminsBean> admins = new ArrayList<>();
        admins = jdbcTemplate.query(sql
                , new RowMapper<AdminsBean>() {
                    @Override
                    public  AdminsBean mapRow(ResultSet re,int rowNum) throws SQLException{
                        AdminsBean admin =new AdminsBean();
                        admin.setAdminId(re.getInt("admin_id"));
                        admin.setAccount(re.getString("account"));
                        admin.setPass(re.getString("pass"));
                        admin.setNickName(re.getString("nick_name"));
                        return admin;
                    }
                },id);
        return admins==null || admins.size()==0?null:admins.get(0);
    }
}
